<?php

namespace Controller\User;

class Setting extends \Controller\Base {

	public function actionIndex() {
		$this->mustLogin();
		$this->setCurrentMenuKey('My');
		$userInfo = $this->currentUserInfo;
		$breedId = $userInfo['BreedId'];
		$userInfo['breed'] = \Business\Breed::instance()->getNameById($breedId);
		$postInfo = array();
		if ($this->isPost()) {
			$postInfo = $this->save();
		}
		foreach ($postInfo as $key => $val) {
			$userInfo[$key] = $val;
		}
		$this->assign('userInfo', $userInfo);
		$this->display();
	}

	private function save() {
		$error = array();
		$dogName = $this->postParam('dogName', true);
		if (!$dogName) {
			$error[] = '请填写名字！';
		} else if (mb_strlen($dogName) > 12) {
			$error[] = '名字请在12个字以内！';
		}
		$breed = $this->postParam('breed');
		$breedId = \Business\Breed::instance()->getBreedIdByName($breed);
		if (!$breedId) {
			$error[] = '请选择正确的品种！';
		}
		$sex = $this->postInt('sex');
		$city = $this->postInt('city');
		$sterilization = $this->postInt('sterilization');
		$y = $this->postInt('y');
		$m = $this->postInt('m');
		$d = $this->postInt('d');
		$birthday = 0;
		if ($y && $m && $d) {
			$birthday = strtotime($y . '-' . $m . '-' . $d . ' 00:00:01');
		}
		$hasChildren = $this->postInt('hasChildren');
		$eatingHabits = !empty($_POST['eatingHabits']) ? implode(',', $_POST['eatingHabits']) : '';
		$weight = $this->postInt('weight');
		if ($weight > 100) {
			$weight = 100;
		}
		$length = $this->postInt('length');
		if ($length > 300) {
			$length = 300;
		}
		$height = $this->postInt('height');
		if ($height > 100) {
			$height = 100;
		}
		$color = $this->postParam('color', true);
		$desc = $this->postParam('desc', true);
		$user = array(
			'Username' => $dogName,
			'BreedId' => $breedId,
			'Sex' => $sex,
			'Sterilization' => $sterilization,
			'Birthday' => $birthday,
			'HasChildren' => $hasChildren,
			'EatingHabits' => $eatingHabits,
			'Weight' => $weight,
			'Length' => $length,
			'Color' => $color,
			'City' => $city,
			'Desc' => $desc,
			'Height' => $height,
		);
		$userId = $this->currentUserInfo['UserId'];
		if (!$error) {
			\Business\User::instance()->updateUserInfo($userId, $user);
			$this->assign('success', '资料修改成功');
			\Lib\Util\Comm::redirect('/home.html');
		}
		$this->assign('error', $error);

		if ($breed) {
			$user['breed'] = $breed;
		}


		return $user;
	}
}